package cn.echogo.framework.widget;

import cn.echogo.ipart.R;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

public class EGRefreshView extends LinearLayout {
	
	private static final String tag = "EGRefreshView";
	
	private int mLastMotionY;
	private View mHeaderView;
	private View mFooterView;
	private ScrollView mScrollView;

	public EGRefreshView(Context context, AttributeSet attrs) {
		super(context, attrs);
//		init();
	}

	public EGRefreshView(Context context) {
		super(context);
//		init();
	}
	
	private void init() {
		initHeader();
		initFooter();
		mScrollView = (ScrollView) findViewById(R.id.scrollview);
	}
	
	private void initHeader() {
		mHeaderView = findViewById(R.id.header_row);
	}
	
	private void initFooter() {
		mFooterView = findViewById(R.id.footer_row);
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {
		int action = event.getAction();
		int y0 = (int)event.getY();
		int y = (int)event.getRawY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			init();
			mLastMotionY = y;
			break;
		case MotionEvent.ACTION_MOVE:
			int deltaY = y - mLastMotionY;
			return isRefreshViewScroll(deltaY);
//			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			break;
		}
		return false;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		int y0 = (int)event.getY();
		int y = (int)event.getRawY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
//			init();
//			mLastMotionY = y;
			break;
		case MotionEvent.ACTION_MOVE:
			int deltaY = y - mLastMotionY;
			LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)mHeaderView.getLayoutParams();
			params.topMargin = deltaY;
			mHeaderView.setLayoutParams(params);
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			
			break;
		}
//		return super.onTouchEvent(event);
		return true;
	}
	
	/**
	 * 是否应该到了父View,即PullToRefreshView滑动
	 * 
	 * @param deltaY , deltaY > 0 是向下运动,< 0是向上运动
	 * @return
	 */
	private boolean isRefreshViewScroll(int deltaY)  {
		LinearLayout.LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();
		if(deltaY > 0 && params.topMargin < 0) {
			Log.d(tag, "DOWN");
			return true;
		} else if(deltaY < 0 && params.topMargin > -mHeaderView.getMeasuredHeight()) {
			Log.d(tag, "UP :: " + params.topMargin);
			return true;				
		}
		return false;
	}
	

}
